<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <!-- <el-form-item label="图书馆id" prop="libraryId">
        <el-input v-model="formData.libraryId" placeholder="请输入图书馆id" />
      </el-form-item> -->
      <el-form-item label="部门" prop="libraryId">
        <el-tree-select
          v-model="formData.libraryId"
          :data="Listbumen"
          :props="{ label: 'name', value: 'id', children: 'children' }"
          placeholder="请选择部门"
          check-strictly
          clearable
          style="width: 350px"
        />
      </el-form-item>
      <el-form-item label="机器人编号" prop="robotCode">
        <el-input v-model="formData.robotCode" placeholder="请输入机器人编号" />
      </el-form-item>
      <el-form-item label="机器人名称" prop="robotName">
        <el-input v-model="formData.robotName" placeholder="请输入机器人名称" />
      </el-form-item>
      <el-form-item label="机器人类型" prop="robotType">
        <el-select v-model="formData.robotType" placeholder="请选择机器人类型">
          <el-option label="智能盘点机器人" value="1" />
          <el-option label="智能还书系统" value="2" />
          <el-option label="智能导览机器人" value="3" />
        </el-select>
      </el-form-item>

      <!-- <el-form-item label="机器人当前电量" prop="currentPower">
        <el-input
          v-model="formData.currentPower"
          placeholder="请输入机器人当前电量"
        />
      </el-form-item> -->
      <!-- <el-form-item label="主板" prop="mainBoard">
        <el-input v-model="formData.mainBoard" placeholder="请输入主板" />
      </el-form-item>
      <el-form-item label="MAC地址" prop="mac">
        <el-input v-model="formData.mac" placeholder="请输入MAC地址" />
      </el-form-item>
      <el-form-item label="充电次数" prop="chargingCount">
        <el-input
          v-model="formData.chargingCount"
          placeholder="请输入充电次数"
        />
      </el-form-item> -->
      <el-form-item label="地点" prop="address">
        <el-input v-model="formData.address" placeholder="请输入地点" />
      </el-form-item>
      <el-form-item label="省市区" prop="district">
        <el-cascader
          v-model="selectedValue"
          :options="options"
          :props="defaultProps"
          placeholder="请选择省市区"
          clearable
          @change="handleChange"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="机器人状态" prop="robotStatus" label-width="100px">
        <el-radio-group v-model="formData.robotStatus">
          <el-radio label="-1">离线</el-radio>
          <el-radio label="0">在线</el-radio>
          <el-radio label="1">故障</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- <el-form-item label="处理器" prop="mainBoardCpu">
        <el-input v-model="formData.mainBoardCpu" placeholder="请输入处理器" />
      </el-form-item>
      <el-form-item label="内存" prop="mainBoardMemory">
        <el-input v-model="formData.mainBoardMemory" placeholder="请输入内存" />
      </el-form-item>
      <el-form-item label="存储设备" prop="mainBoardStorageDevice">
        <el-input v-model="formData.mainBoardStorageDevice" placeholder="请输入存储设备" />
      </el-form-item>
      <el-form-item label="处理器" prop="androidCpu">
        <el-input v-model="formData.androidCpu" placeholder="请输入处理器" />
      </el-form-item>
      <el-form-item label="内存" prop="androidMemory">
        <el-input v-model="formData.androidMemory" placeholder="请输入内存" />
      </el-form-item>
      <el-form-item label="存储设备" prop="androidStorageDevice">
        <el-input v-model="formData.androidStorageDevice" placeholder="请输入存储设备" />
      </el-form-item>
      <el-form-item label="MAC地址" prop="androidStorageMac">
        <el-input v-model="formData.androidStorageMac" placeholder="请输入MAC地址" />
      </el-form-item>
      <el-form-item label="麦克风" prop="microphone">
        <el-input v-model="formData.microphone" placeholder="请输入麦克风" />
      </el-form-item>
      <el-form-item label="天线" prop="antenna">
        <el-input v-model="formData.antenna" placeholder="请输入天线" />
      </el-form-item>
      <el-form-item label="雷达状态(0:异常;1:正常)" prop="radarStatus">
        <el-radio-group v-model="formData.radarStatus">
          <el-radio value="1">请选择字典生成</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="测距模组状态(0:异常;1:正常)" prop="moduleStatus">
        <el-radio-group v-model="formData.moduleStatus">
          <el-radio value="1">请选择字典生成</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="超声波状态(0:异常;1:正常)" prop="waveStatus">
        <el-radio-group v-model="formData.waveStatus">
          <el-radio value="1">请选择字典生成</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="轮毂电机状态(0:异常;1:正常)" prop="motorStatus">
        <el-radio-group v-model="formData.motorStatus">
          <el-radio value="1">请选择字典生成</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="安卓板状态(0:异常;1:正常)" prop="androidStatus">
        <el-radio-group v-model="formData.androidStatus">
          <el-radio value="1">请选择字典生成</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="传感器种类及规模" prop="sensorTypeScale">
        <el-input v-model="formData.sensorTypeScale" placeholder="请输入传感器种类及规模" />
      </el-form-item>
      <el-form-item label="动力系统信息" prop="powerInfo">
        <el-input v-model="formData.powerInfo" placeholder="请输入动力系统信息" />
      </el-form-item> -->
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading"
        >确 定</el-button
      >
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { RobotApi, RobotVO } from "@/api/health/robot";
import jsonData from "@/views/health/robot/jsonData.json";
/** 机器人 表单 */
defineOptions({ name: "RobotForm" });

const { t } = useI18n(); // 国际化
const message = useMessage(); // 消息弹窗

const dialogVisible = ref(false); // 弹窗的是否展示
const dialogTitle = ref(""); // 弹窗的标题
const formLoading = ref(false); // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref(""); // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  libraryId: undefined,
  robotType: undefined,
  robotCode: undefined,
  robotName: undefined,
  robotStatus: undefined,
  currentPower: undefined,
  mainBoard: undefined,
  mac: undefined,
  chargingCount: undefined,
  address: undefined,
  province: undefined,
  city: undefined,
  district: undefined,
  mainBoardCpu: undefined,
  mainBoardMemory: undefined,
  mainBoardStorageDevice: undefined,
  androidCpu: undefined,
  androidMemory: undefined,
  androidStorageDevice: undefined,
  androidStorageMac: undefined,
  microphone: undefined,
  antenna: undefined,
  radarStatus: undefined,
  moduleStatus: undefined,
  waveStatus: undefined,
  motorStatus: undefined,
  androidStatus: undefined,
  sensorTypeScale: undefined,
  powerInfo: undefined,
});
const formRef = ref(); // 表单 Ref
const formRules = reactive({
  // ↓↓↓ 新增部门校验
  libraryId: [{ required: true, message: "请选择部门", trigger: "change" }],
  robotCode: [
    { required: true, message: "机器人编号不能为空", trigger: "blur" },
  ],
  robotName: [
    { required: true, message: "机器人名称不能为空", trigger: "blur" },
  ],
  robotType: [
    { required: true, message: "请选择机器人机器人类型", trigger: "change" },
  ],
  robotStatus: [
    { required: true, message: "请选择机器人状态", trigger: "change" },
  ],
});
// 定义省市区数据
const options = ref([]);
const selectedValue = ref([]);
// 配置项
const defaultProps = {
  value: "value", // 节点值的字段名
  label: "label", // 节点显示文本的字段名
  children: "children", // 子节点的字段名
};

// 处理选择变化
const handleChange = (value) => {
  //console.log("当前选择的值（数组格式）:", value);

  // 解构数组，提取出省、市、区
  const [province, city, district] = value;

  // 将提取到的值放入 queryParams 对象
  formData.value.province = province;
  formData.value.city = city;
  formData.value.district = district;
  //console.log("查询参数:", queryParams);
};
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true;
  dialogTitle.value = t("action." + type);
  formType.value = type;
  resetForm();
  // 修改时，设置数据
  if (id) {
    formLoading.value = true;
    try {
      formData.value = await RobotApi.getRobot(id);
    } finally {
      formLoading.value = false;
    }
  }
};
defineExpose({ open }); // 提供 open 方法，用于打开弹窗
import * as DeptApi from "@/api/system/dept";
const flatList = ref<any[]>([]);
/** 查询列表 */
const getBUList = async () => {
  const deptOptions = await DeptApi.getSimpleDeptList();
  console.log(deptOptions, "deptOptions");
  flatList.value = deptOptions; // 保存原始扁平数组
};
onMounted(() => {
  getBUList();
});

/** 真正的树形数据（一次性 computed） */
const Listbumen = computed(() => listToTree(flatList.value, 0));

onMounted(() => {
  getBUList();
});

function listToTree(arr: any[], rootId = 0) {
  return arr
    .filter((item) => item.parentId === rootId)
    .map((item) => ({
      ...item,
      children: listToTree(arr, item.id),
    }));
}
/** 提交表单 */
const emit = defineEmits(["success"]); // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate();
  // 提交请求
  formLoading.value = true;
  try {
    const data = formData.value as unknown as RobotVO;
    if (formType.value === "create") {
      if (formData.value.city == "市辖区") {
        formData.value.city = formData.value.district;
        formData.value.district = undefined;
      }
      await RobotApi.createRobot(data);
      message.success(t("common.createSuccess"));
    } else {
      if (formData.value.city == "市辖区") {
        formData.value.city = formData.value.district;
        formData.value.district = undefined;
      }
      await RobotApi.updateRobot(data);
      message.success(t("common.updateSuccess"));
    }
    dialogVisible.value = false;
    // 发送操作成功的事件
    emit("success");
  } finally {
    formLoading.value = false;
  }
};

/** 重置表单 */
const resetForm = () => {
  selectedValue.value = [];
  formData.value = {
    id: undefined,
    libraryId: undefined,
    robotType: undefined,
    robotCode: undefined,
    robotName: undefined,
    robotStatus: undefined,
    currentPower: undefined,
    mainBoard: undefined,
    mac: undefined,
    chargingCount: undefined,
    address: undefined,
    province: undefined,
    city: undefined,
    district: undefined,
    mainBoardCpu: undefined,
    mainBoardMemory: undefined,
    mainBoardStorageDevice: undefined,
    androidCpu: undefined,
    androidMemory: undefined,
    androidStorageDevice: undefined,
    androidStorageMac: undefined,
    microphone: undefined,
    antenna: undefined,
    radarStatus: undefined,
    moduleStatus: undefined,
    waveStatus: undefined,
    motorStatus: undefined,
    androidStatus: undefined,
    sensorTypeScale: undefined,
    powerInfo: undefined,
  };
  formRef.value?.resetFields();
};
/** 初始化 **/
onMounted(() => {
  // 遍历所有的城市，包括直辖市和其他省、自治区
  for (const province in jsonData) {
    const provinceData = {
      value: province,
      label: province,
      children: [],
    };

    // 遍历该省下的每个地级市
    for (const city in jsonData[province]) {
      const cityData = {
        value: city,
        label: city,
        children: [],
      };

      // 获取市辖区数据
      const districts = jsonData[province][city];
      if (districts && districts.length > 0) {
        cityData.children = districts.map((district) => ({
          value: district,
          label: district,
        }));
        provinceData.children.push(cityData);
      }
    }

    if (provinceData.children.length > 0) {
      options.value.push(provinceData);
    }
  }
});
</script>
